package com.yupi.springbootinit.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Pair;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.config.WxOpenConfig;
import com.yupi.springbootinit.constant.FileConstant;
import com.yupi.springbootinit.constant.MapConstant;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.manager.CosManager;
import com.yupi.springbootinit.model.dto.file.UploadFileRequest;
import com.yupi.springbootinit.model.dto.orders.OrdersQueryRequest;
import com.yupi.springbootinit.model.dto.teacher.TeacherChooseOrderRequest;
import com.yupi.springbootinit.model.dto.teacher.TeacherUpdateMyRequest;
import com.yupi.springbootinit.model.dto.user.*;
import com.yupi.springbootinit.model.entity.Orders;
import com.yupi.springbootinit.model.entity.Teachers;
import com.yupi.springbootinit.model.entity.Temporaryorders;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.enums.FileUploadBizEnum;
import com.yupi.springbootinit.model.vo.LoginTeacherVO;
import com.yupi.springbootinit.model.vo.LoginUserVO;
import com.yupi.springbootinit.model.vo.UserVO;
import com.yupi.springbootinit.service.*;
import com.yupi.springbootinit.utils.AlgorithmUtils;
import com.yupi.springbootinit.utils.MapUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.yupi.springbootinit.service.impl.UserServiceImpl.SALT;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/teacher")
@Slf4j
public class TeachersController {

    @Resource
    private UserService userService;

    @Resource
    private TeachersService teachersService;

    @Resource
    private OrdersService ordersService;

    @Resource
    private TemporaryordersService temporaryordersService;

    @Resource
    private FileService fileService;

    @Resource
    private WxOpenConfig wxOpenConfig;

    @Resource
    private CosManager cosManager;

    // region 登录相关

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return null;
        }
        long result = teachersService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<LoginTeacherVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LoginTeacherVO loginUserVO = teachersService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 用户登录（微信开放平台）
     */
    @GetMapping("/login/wx_open")
    public BaseResponse<LoginUserVO> userLoginByWxOpen(HttpServletRequest request, HttpServletResponse response,
            @RequestParam("code") String code) {
        WxOAuth2AccessToken accessToken;
        try {
            WxMpService wxService = wxOpenConfig.getWxMpService();
            accessToken = wxService.getOAuth2Service().getAccessToken(code);
            WxOAuth2UserInfo userInfo = wxService.getOAuth2Service().getUserInfo(accessToken, code);
            String unionId = userInfo.getUnionId();
            String mpOpenId = userInfo.getOpenid();
            if (StringUtils.isAnyBlank(unionId, mpOpenId)) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "登录失败，系统错误");
            }
            return ResultUtils.success(userService.userLoginByMpOpen(userInfo, request));
        } catch (Exception e) {
            log.error("userLoginByWxOpen error", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "登录失败，系统错误");
        }
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginTeacherVO> getLoginUser(HttpServletRequest request) {
        Teachers user = teachersService.getLoginUser(request);
        return ResultUtils.success(teachersService.getLoginUserVO(user));
    }

    // endregion

    // region 增删改查

    /**
     * 创建用户
     *
     * @param userAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        // 默认密码 12345678
        String defaultPassword = "12345678";
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + defaultPassword).getBytes());
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest,
            HttpServletRequest request) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    // endregion

    /**
     * 更新个人信息
     *
     * @param userUpdateMyRequest
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    public BaseResponse<Boolean> updateMyUser(@RequestBody TeacherUpdateMyRequest userUpdateMyRequest,
            HttpServletRequest request) {
        if (userUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Teachers loginUser = teachersService.getLoginUser(request);
        Teachers user = new Teachers();
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(loginUser.getId());
        boolean result = teachersService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    @GetMapping("/searchByName")
    public BaseResponse<List<Teachers>> searchUsersByName(String username, HttpServletRequest request) {
        QueryWrapper<Teachers> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("userName", username);
        }
        List<Teachers> userList = teachersService.list(queryWrapper);
        return ResultUtils.success(userList);
    }

    @GetMapping("/searchById")
    public BaseResponse<List<Teachers>> searchUsersById(long id, HttpServletRequest request) {
        QueryWrapper<Teachers> queryWrapper = new QueryWrapper<>();
        if (id>=0) {
            queryWrapper.eq("id", id);
        }
        List<Teachers> userList = teachersService.list(queryWrapper);
        List<Teachers> list = userList.stream().map(user -> teachersService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchUsersByTags(@RequestParam(required = false) List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<User> userList = userService.searchUsersByTags(tagNameList);
        return ResultUtils.success(userList);
    }

    //推荐教师
    @GetMapping("/recommend")
    public BaseResponse<Page<Teachers>> recommendUsers(long pageSize,long pageNum,HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        // 无缓存，查数据库
        QueryWrapper<Teachers> queryWrapper = new QueryWrapper<>();
        Page<Teachers> userPage = teachersService.page(new Page<>(pageNum, pageSize), queryWrapper);

        return ResultUtils.success(userPage);
    }

    @PostMapping("/addTeacherTags")
    public BaseResponse<Boolean> addTeacherTags(@RequestParam(required = false) List<String> tagNameList,
                                              HttpServletRequest request) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Teachers loginUser = teachersService.getLoginUser(request);
        Teachers user = new Teachers();
        BeanUtils.copyProperties(loginUser, user);
        user.setId(loginUser.getId());
        // 将标签列表转换为 JSON 字符串
        Gson gson = new Gson();
        String tagsJson = gson.toJson(tagNameList);
        user.setTags(tagsJson);
        boolean result = teachersService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    //订单列表
    @GetMapping("/myOrdersList")
    public BaseResponse<Page<Orders>> getMyOrdersList(long pageSize,long pageNum,HttpServletRequest request) {
        Teachers loginUser = teachersService.getLoginUser(request);
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacherId", loginUser.getId());
        List<Orders> ordersList = ordersService.list(queryWrapper);
        if (ordersList == null) {
            return ResultUtils.success(null);
        }
        int size = ordersList.size();
        // 创建分页对象
        Page<Orders> page = new Page<>(pageSize, pageNum);
        // 执行分页查询
        Page<Orders> ordersPage = ordersService.page(page, queryWrapper);
        return ResultUtils.success(ordersPage);
    }

    //订单详情
    @GetMapping("/getOneOrder")
    public BaseResponse<Orders> getOneOrder(long id,HttpServletRequest request) {
        Teachers loginUser = teachersService.getLoginUser(request);
        Orders order = ordersService.getById(id);
        if (!order.getTeacherId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(order);
    }

    //订单详情
    @GetMapping("/getMyOrders")
    public BaseResponse<List<Orders>> getMyOrders(HttpServletRequest request) {
        Teachers loginUser = teachersService.getLoginUser(request);
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacherId", loginUser.getId());
        List<Orders> ordersList = ordersService.list(queryWrapper);
        if (ordersList == null) {
            return ResultUtils.success(null);
        }
        return ResultUtils.success(ordersList);
    }

    /**
     * 教师接单
     *
     * @param teacherChooseOrderRequest
     * @param request
     * @return
     */
    @PostMapping("/addTempOrder")
    public BaseResponse<Boolean> chooseOrder(TeacherChooseOrderRequest teacherChooseOrderRequest,
                                              HttpServletRequest request) {
        if (teacherChooseOrderRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        MultipartFile file = teacherChooseOrderRequest.getAnswerDirectory();
        Teachers loginUser = teachersService.getLoginUser(request);
        Long teacherId = loginUser.getId();
        Orders order = ordersService.getById(teacherChooseOrderRequest.getOrderId());
        Temporaryorders tempOrder = new Temporaryorders();
        tempOrder.setOrderId(order.getOrderId());
        tempOrder.setUserId(order.getUserId());
        tempOrder.setTeacherId(teacherId);
        tempOrder.setOrderStatus(0);
        tempOrder.setQuestionFile(order.getQuestionFile());
        temporaryordersService.save(tempOrder);
        Long newId = tempOrder.getId();
        //上传回答
        UploadFileRequest uploadFileRequest = new UploadFileRequest();
        uploadFileRequest.setBiz("order_answer");
        String fileUrl = "";
        if (file != null) {
            fileUrl = fileService.uploadAnswer(file,uploadFileRequest,newId);
        }
        tempOrder.setAnswerDirectory(fileUrl);
        Boolean result = temporaryordersService.updateById(tempOrder);
        return ResultUtils.success(result);
    }

    @GetMapping("/getTempOrderList")
    public BaseResponse<List<Temporaryorders>> getTempOrderList(HttpServletRequest request) {
        Teachers loginUser = teachersService.getLoginUser(request);
        QueryWrapper<Temporaryorders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacherId", loginUser.getId());
        List<Temporaryorders> tempOrderList = temporaryordersService.list(queryWrapper);
        if (tempOrderList == null) {
            return ResultUtils.success(null);
        }
        return ResultUtils.success(tempOrderList);
    }

    /**
     * 删除临时订单
     *
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/deleteTempOrder")
    public BaseResponse<Boolean> deleteTempOrder(long id, HttpServletRequest request) {
       Teachers loginUser = teachersService.getLoginUser(request);
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = teachersService.deleteTempOrder(id, loginUser);
        return ResultUtils.success(b);
    }

    @GetMapping("/getOrderList")
    public BaseResponse<List<Orders>> getOrderList(long num ,HttpServletRequest request) {
        Teachers loginUser = teachersService.getLoginUser(request);
        return ResultUtils.success(teachersService.matchOrders(num,loginUser));
    }

    /**
     * 完成订单
     *
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/confirmOrder")
    public BaseResponse<Boolean> confirmOrder(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Teachers loginUser = teachersService.getLoginUser(request);
        return ResultUtils.success(teachersService.confirmOrder(id,loginUser));
    }

    /**
     * 更新评论
     *
     * @param request
     * @return
     */
    @PostMapping("/updateComments")
    public BaseResponse<Boolean> updateComments(HttpServletRequest request) {
        Teachers loginUser = teachersService.getLoginUser(request);
        teachersService.updateComment(loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 获取评论
     */
    @GetMapping("/getComments")
    public BaseResponse<String> getComments(long id,HttpServletRequest request) {
        Teachers teacher = teachersService.getById(id);
        String comments = teacher.getComments();
        return ResultUtils.success(comments);
    }

    /**
     * 上传头像
     *
     * @param multipartFile
     * @param uploadFileRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/user_avatar")
    public BaseResponse<String> uploadAvatar(@RequestPart("file") MultipartFile multipartFile,
                                             UploadFileRequest uploadFileRequest, HttpServletRequest request) {
        String biz = uploadFileRequest.getBiz();
        FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(biz);
        if (fileUploadBizEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        validFile(multipartFile, fileUploadBizEnum);
        Teachers loginUser = teachersService.getLoginUser(request);
        // 文件目录：根据业务、用户来划分
        String uuid = RandomStringUtils.randomAlphanumeric(2);
        String filename = uuid + "-" + multipartFile.getOriginalFilename();
        String filepath = String.format("/%s/%s/%s", fileUploadBizEnum.getValue(), loginUser.getId(), filename);
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filepath, file);
            //保存头像
            String user_avatar = FileConstant.COS_HOST + filepath;
            loginUser.setUserAvatar(user_avatar);
            teachersService.updateById(loginUser);
            // 返回可访问地址
            return ResultUtils.success(FileConstant.COS_HOST + filepath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }

    /**
     * 上传回答
     *
     * @param multipartFile
     * @param uploadFileRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/anwser")
    public BaseResponse<String> uploadAnswer(@RequestPart("file") MultipartFile multipartFile,
                                               UploadFileRequest uploadFileRequest, HttpServletRequest request,long orderId) {
        Teachers loginUser = teachersService.getLoginUser(request);
        Long id = loginUser.getId();
        Orders order = ordersService.getById(orderId);
        if (!order.getTeacherId().equals(id)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"不是该用户的订单");
        }
        String answer = fileService.uploadAnswer(multipartFile, uploadFileRequest, orderId);
        order.setAnswerDirectory(answer);
        ordersService.updateById(order);
        return ResultUtils.success(answer);
    }
    /**
     * 校验文件
     *
     * @param multipartFile
     * @param fileUploadBizEnum 业务类型
     */
    private void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 1024 * 1024L;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 1M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
        }
    }

    /**
     * 获取全部用户列表，删除的不要
     */
    @GetMapping("/getTeachers")
    public BaseResponse<List<Teachers>> getTeachersList() {
        QueryWrapper<Teachers> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("isDelete", 1);
        List<Teachers> userList = teachersService.list(queryWrapper);
        return ResultUtils.success(userList);
    }

    /**
     * 根据教师地址和订单地址匹配
     */
    @PostMapping("/matchGeo")
    public BaseResponse<List<Pair<Orders, Integer>>> matchGeo(int num, HttpServletRequest request) {
        Teachers loginUser = teachersService.getLoginUser(request);
        Long id = loginUser.getId();
        String ranges = loginUser.getRanges();
        String location = MapUtils.getLocation(ranges);
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderStatus", 0);
        List<Orders> ordersList = ordersService.list(queryWrapper);
        List<Pair<Orders, Integer>> list = new ArrayList<>();
        for (Orders order : ordersList) {
            String offlineAddress = order.getOfflineAddress();
            String location1 = MapUtils.getLocation(offlineAddress);
            String destination = MapUtils.getDestination(location, location1);
            int distance = Integer.parseInt(destination);
            list.add(new Pair<>(order, distance));
        }
        // 按距离从小到大排序
        List<Pair<Orders, Integer>> topUserPairList = list.stream()
                .sorted((a, b) -> Integer.compare(a.getValue(), b.getValue()))
                .limit(num)
                .collect(Collectors.toList());
        return ResultUtils.success(topUserPairList);
    }
}
